<template>
  <div class="main">
    <MyHeader @search="handleSearch"></MyHeader>
    <el-card class="bottom">
      <div class="table-overview">
        <div class="left">
          <span>{{ tableName }}</span>
          <span class="total"
            >共
            <span>{{ pagination.total }}</span>
            条记录
          </span>

          <el-button
            class="delete-btn"
            type="danger"
            v-if="computedSelectedTable.length >= 2"
            @click="handleDeleteList"
            >删除{{ computedSelectedTable.length }}条</el-button
          >
        </div>
        <div class="right">
          <el-button type="primary" @click="exportSelected">导出选中</el-button>
          <el-button type="primary" @click="showExportAllDialog"
            >导出全部</el-button
          >

          <el-button type="primary" @click="showAddDialog">新增</el-button>
        </div>
      </div>

      <AccountTable
        :tableData="tableData"
        :selectedTable="selectedTable"
        :pagination="pagination"
        @edit="showEditDialog"
        @resetPwd="handleResetPwd"
        @delete="showDeleteDialog"
        @selectionChange="handleSelectionChange"
        @currentChange="handleCurrentChange"
        @updateCell="handleUpdateCell"
      >
      </AccountTable>

      <AddDialog
        :addDialogVisible="addDialogVisible"
        :form="addForm"
        @closeAddDialog="handleCloseAddDialog"
        @confirm="handleConfirmAdd"
      ></AddDialog>

      <EditDialog
        :editForm="editForm"
        :editDialogVisible="editDialogVisible"
        @closeEditDialog="handleCloseEditDialog"
        @update="handleUpdate"
      >
      </EditDialog>

      <DeleteDialog
        :deleteDialogVisible="deleteDialogVisible"
        @closeDeleteDialog="handleCloseDeleteDialog"
        @confirm="handleDelete"
      >
        确认删除这行数据吗？
      </DeleteDialog>

      <ExportDialog
        :exportAllDialogVisible="exportAllDialogVisible"
        :tableData="exportTableData"
        @closeExportAllDialog="handleCloseExportAllDialog"
      ></ExportDialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { utils, writeFile } from "xlsx";

import MyHeader from "./components/MyHeader.vue";
import AccountTable from "./components/AccountTable.vue";
import AddDialog from "./components/AddDialog.vue";
import EditDialog from "./components/EditDialog.vue";
import DeleteDialog from "@/components/DeleteDialog.vue";
import ExportDialog from "./components/ExportDialog.vue";

import { computed, reactive, toRefs } from "vue";
import lodash from "lodash";
import { ElMessage } from "element-plus";

import { UserCommonHeads } from "@/data/tableConfig.ts";
import { userCommonMap } from "@/data/tableMap.ts";

import {} from "@/api/organizationManage/index.ts";
import {
  getList,
  addUSer,
  editUser,
  resetPwd,
  deleteUser,
  deleteUserList,
} from "@/api/user/index.ts";
import { useStore } from "vuex";
import { getAll } from "@/api/user/index.ts";

const tableName = "用户列表";
let tableData: IObj[] = reactive([]);

const state = reactive({
  addDialogVisible: false,
  editDialogVisible: false,
  deleteDialogVisible: false,
  exportAllDialogVisible: false,
  editForm: {},
});

const {
  addDialogVisible,
  editDialogVisible,
  deleteDialogVisible,
  exportAllDialogVisible,
  editForm,
} = { ...toRefs(state) };

// 分页功能
const pagination = reactive({
  // 当前页
  currentPage: 1,

  // 一页数据条数
  pageSize: 10,

  // 总数据条数
  total: 0,
});

const handleCurrentChange = (page: number) => {
  getDataList(page, pagination.pageSize);
};

async function getDataList(page: number, limit: number, condition?: IObj) {
  const { data } = await getList({
    page,
    limit,
    ...condition,
  });

  if (data.code === 200) {
    pagination.total = data.data.total;

    // 清空数组
    tableData.splice(0, tableData.length);

    for (const item of data.data.records) {
      tableData.push({
        rowId: item._id,
        phone: item.phone,
        username: item.userName,
        role: item.role,
        organization: item.organization,
      });
    }

    console.log(tableData);
  }
}

function initTableData() {
  getDataList(pagination.currentPage, pagination.pageSize);
}

initTableData();

// 事件

// 查询功能
const handleSearch = (searchForm: any) => {
  const obj: IObj = {};

  for (const item in searchForm) {
    if (searchForm[item] !== "") {
      obj[item] = searchForm[item];
    }
  }

  getDataList(pagination.currentPage, pagination.pageSize, obj);
};

// 添加社团功能
const addForm = reactive({
  username: "",
  phone: "",
  organization: "",
  role: ''
});
const showAddDialog = () => {
  addDialogVisible.value = true;
};

const handleCloseAddDialog = () => {
  addDialogVisible.value = false;
};

const handleConfirmAdd = async () => {
  handleCloseAddDialog();

  const params: any = {
    userName: addForm.username,
    phone: addForm.phone,
    role: addForm.role,
  };

  if (addForm.organization !== '') {
    params.organization = addForm.organization;
  }

  const { data } = await addUSer(params);
  if (data.code === 200) {
    ElMessage({
      message: "新增成功",
      type: "success",
    });

    initTableData();

    // addForm.username = "";
    // addForm.phone = "";
    // addForm.organization = "";
    // addForm.role = "";
  }
};
// 添加功能结束

// 编辑功能
const showEditDialog = (row: IOrganizationTable) => {
  editDialogVisible.value = true;
  editForm.value = lodash.cloneDeep(row);

  // (editForm.value as IObj).organization += "";

  console.log(editForm.value);
};

const handleCloseEditDialog = () => {
  editDialogVisible.value = false;
};

const handleUpdate = async () => {
  const obj: IOrganizationTable = editForm.value as IOrganizationTable;

  handleCloseEditDialog();

  const params: any = {
    _id: obj.rowId,
    userName: obj.username,
    phone: obj.phone,
    role: obj.role,
  };

  if (obj.role === '管理员') {
    params.organization = null;
  } else {
    params.organization = obj.organization;
  }

  const { data } = await editUser(params);

  if (data.code === 200) {
    ElMessage({
      message: "更新成功",
      type: "success",
    });

    initTableData();
  }
};

const handleUpdateCell = async (index: number, attribute: string) => {
  const params: any = {
    _id: tableData[index].rowId,
    userName: tableData[index].username,
    phone: tableData[index].phone,
    role: tableData[index].role,
  };

  if (tableData[index].role === '管理员') {
    params.organization = null;
  } else {
    params.organization = tableData[index].organization;
  }


  const { data } = await editUser(params);

  if (data.code === 200) {
    initTableData();

    ElMessage({
      message: "更新成功",
      type: "success",
    });
  }
};

// 编辑功能结束

const handleResetPwd = async (userId: number) => {
  const { data } = await resetPwd(userId);

  if (data.code === 200) {
    ElMessage({
      message: "重置密码成功",
      type: "success",
    });

    initTableData();
  }
};

// 删除功能
let deleteId: number;
const showDeleteDialog = (row: IOrganizationTable) => {
  deleteId = row.rowId;
  deleteDialogVisible.value = true;
};

const handleCloseDeleteDialog = () => {
  deleteDialogVisible.value = false;
};

const handleDelete = async () => {
  handleCloseDeleteDialog();

  const { data } = await deleteUser(deleteId);
  if (data.code === 200) {
    ElMessage({
      message: "删除成功",
      type: "success",
    });

    if (selectedTable[pagination.currentPage] !== undefined) {
      selectedTable[pagination.currentPage] = selectedTable[
        pagination.currentPage
      ].filter((item: IObj) => item.rowId != deleteId);
    }
    initTableData();
  }
};

const handleDeleteList = async () => {
  const idList = [];
  for (const item of computedSelectedTable.value) {
    idList.push(item.rowId);
  }

  const { data } = await deleteUserList(idList);
  if (data.code === 200) {
    ElMessage({
      message: "删除成功",
      type: "success",
    });

    for (const deleteId of idList) {
      const page = Math.ceil(pagination.total / pagination.pageSize);

      for (let i = 1; i <= page; i++)
      if (selectedTable[i] !== undefined) {
        selectedTable[i] = selectedTable[i].filter((item: IObj) => item.rowId != deleteId);
      }
    }

    initTableData();
  }
};

// 删除功能结束

// 导出功能

const exportTableData: IObj[] = reactive([]);

const showExportAllDialog = async () => {
  const { data: res } = await getAll();

  if (res.code === 200) {
    // 清空数组
    exportTableData.splice(0, exportTableData.length);

    for (const item of res.data) {
      exportTableData.push({
        rowId: item._id,
        phone: item.phone,
        username: item.userName,
        role: item.role,
        organization: item.organization,
      });
    }
  }

  exportAllDialogVisible.value = true;
};

const handleCloseExportAllDialog = () => {
  exportAllDialogVisible.value = false;
};

let selectedTable: IObj = reactive({});

const computedSelectedTable = computed(() => {
  const result = [];

  for (const item in selectedTable) {
    if (selectedTable[item].length != 0) {
      result.push(...selectedTable[item]);
    }
  }
  return result;
});
const handleSelectionChange = (selection: IOrganizationTable[]) => {
  selectedTable[pagination.currentPage] = lodash.cloneDeep(selection);
};

const exportSelected = () => {
  if (computedSelectedTable.value.length <= 0) {
    return;
  }

  exportTableData.splice(0, exportTableData.length);

  for (const row of computedSelectedTable.value) {

    exportTableData.push(row);
  }

  exportAllDialogVisible.value = true;
};
</script>

<style lang="less" scoped>
.bottom {
  margin-top: 28px;

  .table-overview {
    display: flex;
    justify-content: space-between;
    height: 60px;
    line-height: 30px;

    .left {
      .total {
        margin-left: 50px;
      }

      .delete-btn {
        margin-left: 20px;
      }
    }
  }
}

:deep(.el-dialog--center .el-dialog__body) {
  padding: 16px calc(var(--el-dialog-padding-primary) + 5px) 0;
}
</style>
